﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TravelWD.Models;
using TravelWD.Manager;

namespace TravelWD.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult Register()
        {
            RegisterModel model = new RegisterModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                using (TravelWDDataContext dataContext = new TravelWDDataContext())
                {
                    if (!dataContext.CheckUsernameExists(model.Username).Value)
                    {
                        dataContext.CreateUser(model.FirstName, model.LastName, model.Username, model.Password, model.EmailID, "", false, Request.ServerVariables[0]);
                        TempData["msg"] = "Successfully registered! Please login!";
                    }
                    else
                    {
                        ModelState.AddModelError("Username", "Username already exists");
                    }
                }
            }

            return View(model);
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            bool isvalid = false;
            if (ModelState.IsValid)
            {
                using (TravelWDDataContext dataContext = new TravelWDDataContext())
                {
                    var result = dataContext.CheckLogin(model.Username, model.Password);
                    foreach (var item in result)
                    {
                        Session["tuid"] = string.Format("{0}~{1}", item.UserID, item.Name);
                        isvalid = true;
                    }
                }

                if (isvalid)
                {
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    TempData["msg"] = "Invalid username or password!";
                }
            }

            return View(model);
        }
    }
}
